<template>
    <div id="table-component">
        
        <div class="table-container flex-center" :style="editSetting?'margin-top: 10px;':''">
            <div class="tablename" style="font-size: 40px;font-weight: 400;color: #333333;">{{tableName}}</div>
            <!-- <el-table :data="tableData" border default-expand-all highlight-current-row :header-cell-style="{background:'#F3F7F8'}"> -->
                <!-- :cell-style="{width:110+'px',height:50+'px'}"  -->
            <el-table  class="num_table" :data="tableData" border   @cell-click="currentChange">
                <el-table-column align="center"  v-for="(item, index) in tableColumn" :key="index + item.key + columnHandle" :label="item.key">
                    <template slot="header" class="row-column" v-if="item.key">
                        <div  slot="reference" @contextmenu="contextmenu($event,index,'column')">
                            <input type="text" :value="item.key" class="t-input" @change="handleChange($event,index)" v-arouse>
                            <span class="flex-center">
                                <i class="el-icon-remove-outline" v-if="index === columnHandle" @click="deleteTableData($event,index,'column')"></i>
                                <i style="margin-left:5px" class="el-icon-circle-plus-outline" v-if="index === columnHandle" @click="addOneColumn(index)"></i>
                            </span>
                        </div>
                    </template>
                    <template slot-scope="scope" class="row-column">
                        <el-popover placement="right" popper-class="set-min-width" width="30" trigger="manual" :value="popoverKey===(scope.$index+'-'+index)">
                            <div class="table-delete" @click.stop="deleteTableData($event,scope.$index,'row')">删除整行</div>
                            <div class="table-delete" @click.stop="deleteTableData($event,index,'column')">删除整列</div>
                            <div class="flex-center" slot="reference" @contextmenu="contextmenu($event,scope.$index,index)">
                                <template v-if="index===0">
                                    <span v-if="scope.$index === rowHandle" class="align-center">
                                        <!-- <i class="el-icon-circle-remove-outline" v-if="scope.$index === tableData.length -1" @click="addOneRow"></i> -->
                                        <i class="el-icon-remove-outline" @click="deleteTableData($event,scope.$index,'row')"></i>
                                        <i style="margin-top:5px" class="el-icon-circle-plus-outline" @click="addOneRow(scope.$index)"></i>
                                    </span>
                                    <input type="text" v-model="scope.row.rowKey" class="t-input" v-arouse>
                                </template>
                                <template v-else>
                                    <input type="text" class="t-input" v-arouse :value="rowValue(scope.$index,index-1)" @change="rowDataChange($event,scope.row.rowKey,scope.$index,index-1)">
                                </template>
                            </div>
                        </el-popover>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div v-if="!editSetting" style="" class="editSetting">
            表格名称： <el-input style="width:300px" v-model="tableName" maxlength="20" placeholder="请输入表格名称" @input="val=>title.name=val||'新建表格'" v-arouse></el-input>
        </div>
        <div class="flex-center chartList"  v-if="!editSetting">
            <div class="make-charts-handle flex-center" @click="createCharts('histogram')">
                <img src="../../../assets/img/histogram.png" alt="">
                <span>
                    生成柱状图
                </span>
            </div>
            <div class="make-charts-handle flex-center" @click="createCharts('line')">
                <img src="../../../assets/img/line.png" alt="">
                <span>
                    生成折线图
                </span>
            </div>
            <div class="make-charts-handle flex-center" @click="createCharts('pie')">
                <img src="../../../assets/img/pie.png" alt="">
                <span>
                    生成饼图
                </span>
            </div>
            <div class="make-charts-handle flex-center" @click="saveTable">
                <img src="../../../assets/img/pie.png" alt="">
                <span>
                    保存表格
                </span>
            </div>
        </div>
        <div slot="footer" class="flex-center" v-else style="margin-top:40px">
            <el-button type="primary" @click="editChartsData" style="margin-right:15px">确 定</el-button>
            <el-button @click="closeDialog">取 消</el-button>
        </div>
        <transition name="charts">
            <div class="charts-dialog flex-center" v-if="showChartsDialog&&!editSetting">
                <div class="charts-dialog-container">
                    <my-charts :chartsData="chartsData" class="charts_size" style="width:100%;height:100%" :showChartsDialog.sync="showChartsDialog"></my-charts>
                </div>
            </div>
        </transition>
        <el-dialog title="提示" :visible.sync="setTableName" width="500px">
            <div class="flex-center">
                表格名称： <el-input v-model="tableName" placeholder="请输入表格名称" v-arouse style="width:300px"></el-input>
            </div>
            <div slot="footer">
                <el-button type="primary" @click="saveTable" :disabled="!tableName">确 定</el-button>
                <el-button @click="cancelSetName">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { contorlMessageCenter } from '../../../../content/utils/event'
import MyCharts from './MyCharts.vue'

const nameMap = {
    histogram: "图表名称-柱状图",
    line: '图表名称-折线图',
    pie: '图表名称-饼图'
}
export default {
    name: 'MyTable',
    components: { MyCharts },
    inject: ['title'],
    props: {
        editSetting: {
            type: Object,
            default: null
        }
    },
    data () {
        return {
            setTableName: false,
            rowHandle: -1,
            columnHandle: -1,
            chartsData: null,
            showChartsDialog: false,
            tableName: '',
            tableData: [],
            tableColumn: [{ key: '' }],
            rowData: [],
            row: 1,
            column: 1,
            popoverKey: '',
            options: [{
                value: 'histogram',
                label: '柱状图'
            }, {
                value: 'line',
                label: '折线图'
            }, {
                value: 'pie',
                label: '饼图'
            }],
            selectType: ''
        }
    },
    created () {
        if (this.$route.params.originPath) {
            this.readFile(this.$route.params.originPath)
        } else {
            if (this.editSetting) {
                this.tableData = this.editSetting.tableData
                this.tableColumn = this.editSetting.tableColumn
                this.rowData = this.editSetting.rowData
                this.tableName = this.editSetting.tableName
                this.selectType = this.editSetting.type
            } else {
                this.title.name = '新建表格'
                this.row = this.$route.params.row
                this.column = this.$route.params.column
                for (let index = 0; index < this.row; index++) {
                    this.addOneRow()
                }
                for (let index = 0; index < this.column; index++) {
                    this.addOneColumn()
                    this.rowData.map(item => {
                        // item.value[index] = Math.round(Math.random() * 40 + 10)
                        item.value[index] = 0
                    })
                }
            }
        }
        document.documentElement.addEventListener('click', this.initPopover)
    },
    beforeDestroy () {
        document.documentElement.removeEventListener('click', this.initPopover)
    },
    methods: {
        initPopover (e) {
            this.popoverKey = ''
            if (e.target.className !== 't-input') {
                this.rowHandle = -1
                this.columnHandle = -1
            }
        },
        addOneColumn (index,) {
            if (this.tableColumn.length >= 13) return
            if (index !== undefined) {
                this.tableColumn.splice(index, 1, ...[this.tableColumn[index], { key: '系列' + this.tableColumn.length }])
                this.rowData.forEach(item => {
                    item.value.splice(index, 1, ...['', item.value[index]])
                })
            } else {
                this.tableColumn.push({ key: '系列' + this.tableColumn.length })
            }
            this._isChange = true
        },
        addOneRow (index) {
            if (this.rowData.length >= 12) return
            const key = '类别' + (this.tableData.length + 1)
            if (index !== undefined) {
                this.tableData.splice(index, 1, ...[this.tableData[index], { rowKey: key }])
                this.rowData.splice(index, 1, ...[this.rowData[index], { rowKey: key, value: Array(this.tableColumn.length - 1).fill(0) }])
            } else {
                this.tableData.push({ rowKey: key })
                this.rowData.push({ rowKey: key, value: Array(this.tableColumn.length - 1).fill(0) })
            }
            this._isChange = true
        },
        handleChange (event, index) {
            event.preventDefault()
            event.target.value === '' ? event.target.value = event.target._value : ''
            const val = event.target.value || ''
            this.tableColumn[index].key = val
            this._isChange = true
        },
        rowDataChange (event, key, scopeIndex, index) {
            event.target.value === '' ? event.target.value = event.target._value : ''
            const val = event.target.value
            this.rowData[scopeIndex].rowKey = key
            this.rowData[scopeIndex].value[index] = val
            this._isChange = true
        },
        rowValue (scopeIndex, index) {
            return this.rowData[scopeIndex].value[index] ? this.rowData[scopeIndex].value[index] : ''
        },
        createCharts (type) {
            //暴力解决确保数据一致,后续自行更改
            this.tableData.forEach((item, index) => {
                this.rowData[index].rowKey = item.rowKey
            })
            this.chartsData = {
                tableColumn: this.tableColumn,
                rowData: this.rowData,
                tableData: this.tableData,
                tableName: this.tableName || nameMap[type],
                type: type
            }
            this.showChartsDialog = true
        },
        closeCharts () {
            this.chartsData = null
            this.showChartsDialog = false
        },
        currentChange (row, column, cell, event) {
            const rowKey = row.rowKey
            const columnLabel = column.label
            this.tableData.some((item, index) => {
                if (item.rowKey === rowKey && !column.label) {
                    this.rowHandle = -1
                    return true
                }
                this.rowHandle = index
                return item.rowKey === rowKey
            })
            this.tableColumn.some((item, index) => {
                this.columnHandle = index
                return item.key === columnLabel
            })
        },
        contextmenu (e, index, columnIndex) {
            this.popoverKey = index + '-' + columnIndex
        },
        deleteTableData (e, index, type) {
            if (type === 'row') {
                if (this.tableData.length <= 1) {
                    this.$message.warning('不能再删除了')
                    return
                }
                this.rowData.splice(index, 1)
                this.tableData.splice(index, 1)
            }
            if (type === 'column') {
                if (this.tableColumn.length <= 1) {
                    this.$message.warning('不能再删除了')
                    return
                }
                this.rowData.forEach(item => {
                    item.value.splice(index - 1, 1)
                })
                this.tableColumn.splice(index, 1)
            }
            this.initPopover()
            this._isChange = true
        },
        closeDialog () {
            this.$emit('closeDialog')
        },
        editChartsData () {
            //暴力解决确保数据一致
            this.tableData.forEach((item, index) => {
                this.rowData[index].rowKey = item.rowKey
            })
            this.$emit('editChartsData', {
                tableData: this.tableData,
                tableColumn: this.tableColumn,
                rowData: this.rowData,
                tableName: this.tableName,
                type: this.selectType
            })
        },
        saveTable (cb) {
            if (!this.tableName) {
                this.setTableName = true
            } else {
                this.setTableName = this.setTableName || false
                this.writeFile()
            }

        },
        cancelSetName () {
            this.tableName = ''
            this.setTableName = false
        },
        writeFile (cb) {
            const editSetting = {
                tableData: this.tableData,
                tableColumn: this.tableColumn,
                rowData: this.rowData,
                tableName: this.tableName,
                type: 'table'
            }
            const fs = require('fs')
            let originPath = this._originPath
            if (originPath) {
                if (fs.existsSync(originPath)) {
                    fs.unlinkSync(originPath)
                }
            }
            const path = require('path')
            const filePath = path.join(window.$DATADIR, 'resc', 'user', 'charts', editSetting.tableName + '_b_s_c_' + Date.now() + editSetting.type.substr(0, 1) + '.json')
            let res = fs.writeFileSync(filePath, new Uint8Array(Buffer.from(JSON.stringify(editSetting))))
            if (!res) {
                this.$message.success('保存成功')
                this._isChange = false
                if (cb) {
                    cb()
                }
            }
        },

        readFile (originPath) {
            const fs = require('fs')
            const path = require('path')
            const fileRes = fs.readFileSync(originPath)
            let fileContent = JSON.parse(fileRes.toString())
            this.tableData = fileContent.tableData
            this.tableColumn = fileContent.tableColumn
            this.rowData = fileContent.rowData
            this.tableName = fileContent.tableName
            this.title.name = this.tableName
            this._originPath = originPath
        }
    },
    beforeRouteLeave (from, to, next) {
        if (this._isChange) {
            this.$confirm('是否保存修改?', '提示', {
                confirmButtonText: '保存',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(_ => {
                this.saveTable(next)
            }).catch(_ => {
                next()
            })
        } else {
            next()
        }
    }
}
</script>

<style lang="scss" scope>
    .el-table::before{
        height: 0 !important;
    }
    // .el-table .el-table__cell{
    //     width: 113px !important;
    //     height: 50px !important;
    //     padding: 0 !important;
    // }
</style>
<style lang="scss" scoped>
.charts-enter-active,
.charts-leave-active {
    transition: opacity 0.5s;
}
.charts-enter,
.charts-leave-to {
    opacity: 0;
}
#table-component {
    width: 100%;
    height: 100%;
    display: flex;
    overflow: hidden;
    justify-content: space-between;
    align-items: center;
    flex-direction: column;
    i[class*="el-icon"] {
        cursor: pointer;
    }
    .make-charts-handle {
        width: 12vw;
        min-width: 190px;
        height: 7.2vh;
        background: #ffffff;
        box-shadow: 0px 1px 60px 0px rgba(184, 203, 215, 0.35);
        border-radius: 8px;
        margin-bottom: 35px;
        &:not(:first-child) {
            margin-left: 10px;
        }
        img {
            width: 2.2vw;
            height: 2.2vw;
            cursor: pointer;
        }
        span {
            color: #606266;
            margin-left: 10px;
            font-size: 24px;
            cursor: pointer;
        }
    }
}
.table-container {
    min-width: 10%;
    display: flex;
    flex-direction: column;
    // flex: 1;
    .tablename{
        position:absolute;
        top:-50px;
        font-size: 36px;
    }
    .num_table{
        position: relative;
        top: 20px;
        // max-width: 1331px;
        max-height: 50vh;
        overflow-y: auto;
    }
    .t-input {
        outline: none;
        border: none;
        // padding: 5px;
        height: 100%;
        width: 100%;
        text-overflow: ellipsis;
        background-color: transparent;
    }
    /deep/.cell {
        display: flex;
        align-items: center;
    }
    .table {
        width: fit-content;
    }
}
.editSetting{
    // margin: 20px 0 40px 0;
    position: absolute;
    top: 54vh;
}
.chartList{
    position: absolute;
    top: 65vh;
}
.table-delete {
    cursor: pointer;
    color: #666666;
    padding: 10px 0;
    text-align: center;
    &:nth-child(1) {
        border-bottom: 1px solid lightgray;
    }
}
.charts-dialog {
    position: fixed;
    width: 100vw;
    height: 100vh;
    top: 0;
    left: 0;
    z-index: 100;
    background-color: rgba(#000, 0.4);
    .charts-dialog-container {
        width: 80vw;
        height: 90vh;
        background-color: #fff;
        border-radius: 8px;
    }
}
/deep/ .el-table .cell {
    // width: 110px !important;
    height: 40px !important;
}

/deep/ .el-table th.gutter {
    display: table-cell !important;
}
@media screen and (max-width: 1600px){
    #table-component {
        width: 100vw;
        height:720px;
        position: relative;
        top: -20px;
        .num_table{
            position: relative;
            top: 0px;
        }
        .editSetting{
            margin: 30px 0 20px 0;
        }
    }
}
</style>